<!--
 * @description 组件管理新增/编辑
 * @author zhanghuan
 * @date 2022/11/8
 -->
<template>
  <el-dialog
    v-el-drag-dialog
    :close-on-click-modal="false"
    :title="row.id ? '编辑组件' : '新建组件'"
    :visible.sync="visible"
    :before-close="onClose"
    center
    width="50%"
    top="10vh"
  >
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-position="right"
      label-width="120px"
      style="padding-right: 10px; height: 400px; overflow: auto"
    >
      <el-form-item label="组件分类">
        <!-- <el-input v-model="row.classifyName" readonly /> -->

        <el-select v-model="ruleForm.classifyId" placeholder="请选择">
          <el-option
            v-for="item in treeData"
            :key="item.id"
            :label="item.classifyName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="组件名称" prop="componentName">
        <el-input
          v-model.trim="ruleForm.componentName"
          placeholder="请输入组件名称"
        />
      </el-form-item>
      <el-form-item label="组件标识" prop="code">
        <el-input v-model.trim="ruleForm.code" placeholder="请输入组件标识" />
      </el-form-item>
      <el-form-item label="组件图片" prop="icon">
        <div v-if="!ruleForm.icon" class="selectbtn" @click="uploadFile.showUpload = true">添加图片</div>
        <img v-else :src="ruleForm.icon" @click="uploadFile.showUpload = true">
        <Upload
          v-if="uploadFile.showUpload"
          ref="upload"
          :accept="uploadFile.accept"
          :limit="1"
          :show-chunks="true"
          :multiple="false"
          :is-oss="isOss"
          :chunk-size="uploadFile.chunksize"
          @close="uploadFile.showUpload = false"
          @success="uploadSuccess"
        >
          <div slot="tip" class="upload-tip">
            <i class="el-icon-info" />
            : 只能上传：图片
          </div>
        </Upload>
        <!-- <el-input v-model.trim="ruleForm.icon" placeholder="请输入组件图标" /> -->
        <!--        <image-upload-->
        <!--            v-if="!courseBelong"-->
        <!--            :key="uploadImg.imagecropperKey"-->
        <!--            v-model="ruleForm.icon"-->
        <!--            :preview-id="uploadImg.viewId"-->
        <!--            :forever="true"-->
        <!--            :width="120"-->
        <!--            :view="uploadImg.view"-->
        <!--            :height="120"-->
        <!--            :no-circle="true"-->
        <!--            :no-rotate="false"-->
        <!--            lang-type="zh"-->
        <!--            :is-oss="isOss"-->
        <!--            @changeOssPath="-->
        <!--              (path) => {-->
        <!--                uploadImg.viewId = path;-->
        <!--              }-->
        <!--            "-->
        <!--          />-->
        <!--          <el-image-->
        <!--            v-else-->
        <!--            style="width: 120px; height: 120px"-->
        <!--            :src="uploadImg.viewId"-->
        <!--            :preview-src-list="[uploadImg.viewId]"-->
        <!--          />-->
      </el-form-item>
      <el-form-item label="组件说明">
        <el-input v-model.trim="ruleForm.comDesc" maxlength="200" type="textarea" placeholder="请输入组件说明" />
      </el-form-item>
      <el-form-item label="组件变量" prop="componentVariable">
        <input-table
          v-model="ruleForm.componentVariable"
          @change="onChangeValidate('componentVariable')"
        />
      </el-form-item>
      <el-form-item label="接口设置" prop="interfaceSetting">
        <input-table
          v-model="ruleForm.interfaceSetting"
          @change="onChangeValidate('interfaceSetting')"
        />
      </el-form-item>
      <el-form-item label="组件关联条件" prop="correlationCondition">
        <input-table
          v-model="ruleForm.correlationCondition"
          @change="onChangeValidate('correlationCondition')"
        />
      </el-form-item>
      <el-form-item label="组件关联后操作" prop="associationAction">
        <input-table
          v-model="ruleForm.associationAction"
          @change="onChangeValidate('associationAction')"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button style="padding: 8px 30px" @click="onClose"> 取消 </el-button>
      <el-button
        style="padding: 8px 30px"
        type="primary"
        :loading="loading"
        @click="submitForm('ruleForm')"
      >
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import InputTable from './inputTable.vue'
import { addComponent, editComponent } from '../api/index'
import Upload from '@/components/upload/index'
import ImageUpload from '@/components/ImageUpload'
export default {
  name: 'ComponentManageForm',
  directives: { elDragDialog },
  components: {
    InputTable, ImageUpload, Upload
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    treeData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      ruleForm: {
        componentName: '',
        comDesc: '',
        code: '',
        icon: '',
        componentVariable: '',
        classifyId: '',
        interfaceSetting: '',
        correlationCondition: '',
        associationAction: ''
      },

      courseBelong: false,
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      uploadFile: {
        showUpload: false,
        accept: 'image/*',
        chunksize: 10 * 1024 * 1024,
        file: '',
        oldfile: ''
      },

      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      rules: {
        componentName: [
          { required: true, message: '请输入组件名称', trigger: 'blur' }
        ],
        code: [{ required: true, message: '请输入组件标识', trigger: 'blur' }]
        // icon: [{ required: true, message: '请输入组件图标', trigger: 'blur' }],
        // componentVariable: [
        //   { required: true, message: '请输入组件变量', trigger: 'change' }
        // ],
        // interfaceSetting: [
        //   { required: true, message: '请输入接口设置', trigger: 'change' }
        // ],
        // correlationCondition: [
        //   { required: true, message: '请输入组件关联条件', trigger: 'change' }
        // ],
        // associationAction: [
        //   { required: true, message: '请输入组件关联后操作', trigger: 'change' }
        // ]
      },
      row: {},
      loading: false,
      view: '/API-DOCUMENT/document/file/download?id='
    }
  },
  methods: {
    // 图标上传完成回调
    uploadSuccess(id, files, ossPath) {
      if (id) {
        if (ossPath !== undefined) {
          this.ruleForm.icon = ossPath
        } else {
          this.ruleForm.icon = this.view + id
        }

        // this.form.videoId.id = id
        // this.form.videoId.name = files[0].name.substring(0, files[0].name.lastIndexOf('.'))
        // this.form.videoId.subjectDuration = files[0].duration
        this.uploadFile.file = files[0]
        this.uploadFile.showUpload = false
      }
    },
    init(row) {
      this.ruleForm = {}
      this.uploadImg = {}
      this.resetForm('ruleForm')
      if (row) {
        this.row = {
          ...row
        }
        if (row.id) {
          this.uploadImg.viewId = row.iconUrl
          this.ruleForm = {
            componentName: row.componentName,
            comDesc: row.comDesc,
            classifyId: row.classifyId,
            code: row.code,
            icon: row.icon,
            componentVariable: row.componentVariable,
            interfaceSetting: row.interfaceSetting,
            correlationCondition: row.correlationCondition,
            associationAction: row.associationAction
          }
        }
      } else {
        this.row = {}
      }
    },

    /**
     * 关闭弹框
     */
    onClose() {
      this.$emit('update:visible', false)
    },

    /**
     * 校验单个表单
     */
    onChangeValidate(field) {
      this.$refs.ruleForm.validateField(field)
    },

    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields()
    },

    /**
     * 提交表单
     */
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const formData = {
            ...this.ruleForm
          }
          this.loading = true
          try {
            if (this.row.id) {
              formData.id = this.row.id
              const { data } = await editComponent(formData)
              this.loading = false
              if (data.code === '200') {
                this.$emit('update')
                this.onClose()
              }
            } else {
              const { data } = await addComponent(formData)
              this.loading = false
              if (data.code === '200') {
                this.$emit('update')
                this.onClose()
              }
            }
          } catch (error) {
            this.loading = false
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.selectbtn {
  display: inline-block;
  width: 120px;
  background: rgba(255, 255, 255, 1);
  @include border-color(1px, dotted, $mainColor);
  border-radius: 4px;
  font-size: 14px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  @include font-color($mainColor);
  text-align: center;
  cursor: pointer;
}
</style>
